package com.kotlin.book.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.kotlin.book.adapter.ShelfBlockItemAdapter
import com.kotlin.book.adapter.ShelfListItemAdapter
import com.kotlin.book.api.BookApi
import com.kotlin.book.databinding.FragmentShelfIndexBinding
import com.kotlin.book.entry.Book

class ShelfFragmentIndex : Fragment() {
    private lateinit var binding: FragmentShelfIndexBinding
    private var showList = true
    private var historyList = listOf<Book>()
    private var collectionList = listOf<Book>()


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentShelfIndexBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        BookApi.getRecommendList(null) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    historyList = it
                    checkDataAndUpdate()
                }
            }
        }
        BookApi.getRecommendList(mapOf("pageSize" to 6)) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    collectionList = it
                    checkDataAndUpdate()
                }
            }
        }
    }

    private fun checkDataAndUpdate() {
        if (historyList.isNotEmpty() && collectionList.isNotEmpty()) {
            updateShowMode()
        }
    }

    fun updateShowMode() {
        if (showList) {
            binding.historyBox.layoutManager = LinearLayoutManager(requireContext())
            binding.historyBox.adapter = ShelfListItemAdapter(historyList)

            binding.collectionBox.layoutManager = LinearLayoutManager(requireContext())
            binding.collectionBox.adapter = ShelfListItemAdapter(collectionList)
        } else {
            binding.historyBox.layoutManager = GridLayoutManager(requireContext(), 3)
            binding.historyBox.adapter = ShelfBlockItemAdapter(historyList)

            binding.collectionBox.layoutManager = GridLayoutManager(requireContext(), 3)
            binding.collectionBox.adapter = ShelfBlockItemAdapter(collectionList)
        }
        showList = !showList
    }
}